package com.example.account.service.impl;

import com.example.account.domain.Account;
import com.example.account.mapper.AccountMapper;
import com.example.account.service.AccountService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;


    @Transactional
    @Override
    public Boolean debit(String userId, int money) {
        Example example = new Example(Account.class);
        example.setForUpdate(true); //行锁
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(Account.FILED_ID, userId);
        Account account = accountMapper.selectOneByExample(example);
        if (account == null) {
            return Boolean.FALSE;
        }

        criteria.andGreaterThanOrEqualTo(Account.FILED_MONEY, money);
        Account updatedAccount = new Account();
        updatedAccount.setMoney(account.getMoney() - money);
        int influceCount = accountMapper.updateByExampleSelective(updatedAccount, example);
        return influceCount == 1;
    }
}
